package api

import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

import (
	"encoding/json"
)

// TextModerationResult 定义文本审核返回结果的结构
type TextModerationResult struct {
	Success bool        `json:"success"`
	Code    int         `json:"code,omitempty"`
	Message string      `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
	Error   string      `json:"error,omitempty"`
}

// CheckText 检查文本内容，返回审核结果
func CheckText(text string) (*TextModerationResult, error) {
	if text == "" {
		return &TextModerationResult{
			Success: false,
			Error:   "text cannot be empty",
		}, nil
	}

	// 构建请求参数
	serviceParams, err := json.Marshal(map[string]interface{}{
		"content": text,
	})
	if err != nil {
		return &TextModerationResult{
			Success: false,
			Error:   "failed to marshal service parameters",
		}, err
	}

	// 配置阿里云客户端
	config := createGreenClientConfig()
	client, err := green20220302.NewClient(config)
	if err != nil {
		return &TextModerationResult{
			Success: false,
			Error:   "failed to create green client",
		}, err
	}

	// 构造请求体
	request := &green20220302.TextModerationPlusRequest{
		Service:           tea.String("query_security_check"),
		ServiceParameters: tea.String(string(serviceParams)),
	}

	// 设置运行时选项
	runtime := &util.RuntimeOptions{
		ReadTimeout:    tea.Int(10000),
		ConnectTimeout: tea.Int(10000),
	}

	// 发起调用
	result, err := client.TextModerationPlusWithOptions(request, runtime)
	if err != nil {
		return &TextModerationResult{
			Success: false,
			Error:   "green moderation failed",
		}, err
	}

	// 处理 HTTP 响应状态码
	if *result.StatusCode != 200 {
		return &TextModerationResult{
			Success: false,
			Code:    int(*result.StatusCode),
			Message: "non-OK HTTP status",
		}, nil
	}

	body := result.Body

	// 处理业务响应码
	if *body.Code != 200 {
		return &TextModerationResult{
			Success: false,
			Code:    int(*body.Code),
			Message: *body.Message,
		}, nil
	}

	// 解析审核结果
	dataBytes, err := json.Marshal(body.Data)
	if err != nil {
		return &TextModerationResult{
			Success: false,
			Error:   "failed to marshal data field",
		}, err
	}

	var moderationData map[string]interface{}
	if err := json.Unmarshal(dataBytes, &moderationData); err != nil {
		return &TextModerationResult{
			Success: false,
			Error:   "failed to parse moderation data",
		}, err
	}

	// 检查是否包含违规内容
	if labels, ok := moderationData["labels"].([]interface{}); ok && len(labels) > 0 {
		return &TextModerationResult{
			Success: false,
			Code:    int(*body.Code),
			Message: "content contains inappropriate material",
			Data:    moderationData,
		}, nil
	}

	// 成功返回结果
	return &TextModerationResult{
		Success: true,
		Data:    moderationData,
	}, nil
}

// createGreenClientConfig 创建并配置阿里云 Green 客户端配置
func createGreenClientConfig() *openapi.Config {
	return &openapi.Config{
		AccessKeyId:     tea.String("LTAI5t6AsUdBoEXLycEhes9L"),
		AccessKeySecret: tea.String("35eK6gzOsBXFS96nDny8ae7SsdWPLw"),
		RegionId:        tea.String("cn-shanghai"),
		Endpoint:        tea.String("green-cip.cn-shanghai.aliyuncs.com"),
		ConnectTimeout:  tea.Int(3000),
		ReadTimeout:     tea.Int(6000),
	}
}
